package com.zhugang.week13.prefixsuffixstatistics;

/**
 * @program algorithms
 * @description: reverseBits
 * @author: chanzhugang
 * @create: 2022/09/23 22:39
 */
public class ReverseBits {

    /**
     * 面试题05.03 翻转数位
     * https://leetcode.cn/problems/reverse-bits-lcci/
     *
     * @param num
     * @return
     */
    public int reverseBig(int num) {
        // 可以将一个数位从0变为1， 求最长的一串1的长度

        // 统计每个0，左边有多少个1，右边有多少个1
        int[] nums = new int[32];
        for (int i = 0; i < 32; i++) {
            // num转为二进制数组
            nums[i] = num & 1;
            num >>= 1;
        }

        int[] leftOneCounts = new int[32];
        int count = 0;
        for (int i = 0; i < 32; i++) {
            // 统计左边1的个数
            leftOneCounts[i] = count;
            if (nums[i] == 1) {
                count++;
            } else {
                count = 0;
            }
        }

        int[] rightOneCounts = new int[32];
        count = 0;

        for (int i = 31; i >= 0; i--) {
            // 统计右边1的个数
            rightOneCounts[i] = count;
            if (nums[i] == 1) {
                count++;
            } else {
                count = 0;
            }
        }

        int ret = 0;
        for (int i = 0; i < 32; i++) {
            // 左边 + 右边 + 可以替换的1个
            ret = Math.max(ret, leftOneCounts[i] + rightOneCounts[i] + 1);

          /*  if (ret < leftOneCounts[i] + rightOneCounts[i] + 1) {
                ret = leftOneCounts[i] + rightOneCounts[i];
            }*/
        }
        return ret;
    }
}